package icerts

import (
	"context"

	"gitee.com/djaf/my-certs/app/classes/blobs"
	"gitee.com/djaf/my-certs/app/classes/certificates"
	"gitee.com/djaf/my-certs/app/data/dxo"
	"gitee.com/djaf/my-certs/app/web/dto"
)

// CertificateServiceImpl ...
type CertificateServiceImpl struct {

	//starter:component

	_as func(certificates.Service) //starter:as("#")

	Dao         certificates.DAO //starter:inject("#")
	ServiceBlob blobs.Service    //starter:inject("#")

}

func (inst *CertificateServiceImpl) _impl() certificates.Service {
	return inst
}

// Find ...
func (inst *CertificateServiceImpl) Find(ctx context.Context, id dxo.CertificateID) (*dto.Certificate, error) {
	o1, err := inst.Dao.Find(nil, id)
	if err != nil {
		return nil, err
	}

	o2, err := certificates.ConvertE2D(o1)
	if err != nil {
		return nil, err
	}

	content, err := inst.ServiceBlob.Find(ctx, o1.Content)
	if err != nil {
		return nil, err
	}

	o2.Content = content.Content
	return o2, nil
}

// List ...
func (inst *CertificateServiceImpl) List(ctx context.Context, query *certificates.Query) ([]*dto.Certificate, error) {
	list, err := inst.Dao.List(nil, query)
	if err != nil {
		return nil, err
	}
	return certificates.ConvertListE2D(list)
}

// Insert ...
func (inst *CertificateServiceImpl) Insert(ctx context.Context, item1 *dto.Certificate) (*dto.Certificate, error) {

	// blob
	blob := new(dto.BLOB)
	blob.Label = "x509.cert"
	blob.ContentType = "application/x-security-pem"
	blob.Content = item1.Content
	blob, err := inst.ServiceBlob.Insert(ctx, blob)
	if err != nil {
		return nil, err
	}

	// cert
	item2, err := certificates.ConvertD2E(item1)
	if err != nil {
		return nil, err
	}
	item2.Content = blob.ID
	item3, err := inst.Dao.Insert(nil, item2)
	if err != nil {
		return nil, err
	}
	return certificates.ConvertE2D(item3)
}
